package com.zking.ssm.intercept;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author小李飞刀
 * @site www.javaxl.com
 * @company xxx公司
 * @create  2022-08-19 10:00
 */
public class OneHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        预处理
        System.out.println("[OneHandlerInterceptor] . preHandle");

//        如果 login/logout 这个请求，就直接放行
        String url = request.getRequestURL().toString();
        if (url.indexOf("/login") > 0 || url.indexOf("/logout") > 0){
            return true;
        }

//        对于请求业务方法， 只有登录过也就是存在session数据，才能访问
        String uname = (String) request.getSession().getAttribute("uname");
        if (uname == null || "".equals(uname)){
            response.sendRedirect("/login.jsp");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        后处理
        System.out.println("[OneHandlerInterceptor] . postHandle。。。");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        完成后执行
        System.out.println("[OneHandlerInterceptor] . afterCompletion。。。");
    }
}
